const {
  storeObjectToCache,
  getObjectFromCache,
  deleteCache,
  clearCache,
  getCacheInfo,
  setBatchCache,
} = require('@app/service/requestAdmin');

// POST /api/cache/store - 存储对象到缓存
exports.cacheStore = async (req, res) => {
  try {
    const { key, data, ttl } = req.body;

    if (!key) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '缓存键(key)是必需的',
        data: null,
      });
    }

    if (!data) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '数据(data)是必需的',
        data: null,
      });
    }

    const result = storeObjectToCache(key, data, ttl);

    return res.status(result.code).json({
      code: result.code,
      success: result.success,
      message: result.message,
      data: result.data || null,
    });
  } catch (error) {
    console.error('存储缓存接口错误:', error);
    return res.status(500).json({
      code: 500,
      success: false,
      message: '服务器内部错误',
      data: null,
    });
  }
};

// GET /api/cache/get/:key - 获取缓存对象
exports.cacheGet = async (req, res) => {
  try {
    const { key } = req.params;

    if (!key) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '缓存键(key)是必需的',
        data: null,
      });
    }

    const result = getObjectFromCache(key);

    return res.status(result.code).json({
      code: result.code,
      success: result.success,
      message: result.message,
      data: result.data,
    });
  } catch (error) {
    console.error('获取缓存接口错误:', error);
    return res.status(500).json({
      code: 500,
      success: false,
      message: '服务器内部错误',
      data: null,
    });
  }
};

// DELETE /api/cache/delete/:key - 删除缓存
exports.cacheDelete = async (req, res) => {
  try {
    const { key } = req.params;

    if (!key) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '缓存键(key)是必需的',
        data: null,
      });
    }

    const result = deleteCache(key);

    return res.status(200).json({
      code: 200,
      success: result,
      message: result ? '缓存删除成功' : '缓存删除失败或不存在',
      data: { key, deleted: result },
    });
  } catch (error) {
    console.error('删除缓存接口错误:', error);
    return res.status(500).json({
      code: 500,
      success: false,
      message: '服务器内部错误',
      data: null,
    });
  }
};

// DELETE /api/cache/clear - 清空所有缓存
exports.cacheClear = async (req, res) => {
  try {
    const result = clearCache();

    return res.status(200).json({
      code: 200,
      success: result,
      message: result ? '缓存清空成功' : '缓存清空失败',
      data: { cleared: result },
    });
  } catch (error) {
    console.error('清空缓存接口错误:', error);
    return res.status(500).json({
      code: 500,
      success: false,
      message: '服务器内部错误',
      data: null,
    });
  }
};

// GET /api/cache/info - 获取缓存信息
exports.cacheInfo = async (req, res) => {
  try {
    const result = getCacheInfo();

    return res.status(200).json({
      code: 200,
      success: true,
      message: '获取缓存信息成功',
      data: result,
    });
  } catch (error) {
    console.error('获取缓存信息接口错误:', error);
    return res.status(500).json({
      code: 500,
      success: false,
      message: '服务器内部错误',
      data: null,
    });
  }
};

// POST /api/cache/batch-store - 批量存储缓存
exports.cacheBatchStore = async (req, res) => {
  try {
    const { dataMap, ttl } = req.body;

    if (!dataMap || typeof dataMap !== 'object') {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '数据映射(dataMap)是必需的，且必须是对象类型',
        data: null,
      });
    }
    const result = setBatchCache(dataMap, ttl);
    const count = Object.keys(dataMap).length;

    return res.status(200).json({
      code: 200,
      success: result,
      message: result ?
        `批量存储成功，共处理 ${count} 个键值对` :
        `批量存储部分失败，共处理 ${count} 个键值对`,
      data: {
        processed: count,
        success: result,
        ttl: ttl || 300000,
        timestamp: Date.now(),
      },
    });
  } catch (error) {
    console.error('批量存储缓存接口错误:', error);
    return res.status(500).json({
      code: 500,
      success: false,
      message: '服务器内部错误',
      data: null,
    });
  }
};

// ============= Lang 配置相关接口 =============

// POST /api/lang/store - 设置语言配置
exports.langStore = async (req, res) => {
  try {
    const { langConfig } = req.body;
    const LANG_CONFIG_CACHE_KEY = 'global_lang_config';

    if (!langConfig || typeof langConfig !== 'object') {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '语言配置(langConfig)是必需的，且必须是对象类型',
        data: null,
      });
    }

    // 验证必要的字段
    const requiredFields = ['default', 'current'];
    for (const field of requiredFields) {
      if (!langConfig[field]) {
        return res.status(400).json({
          code: 400,
          success: false,
          message: `缺少必要字段: ${field}`,
          data: null,
        });
      }
    }

    // 添加时间戳和来源信息
    const enhancedLangConfig = {
      ...langConfig,
      timestamp: Date.now(),
      source: 'api',
    };

    const result = storeObjectToCache(LANG_CONFIG_CACHE_KEY, enhancedLangConfig, 600000);

    return res.status(result.code).json({
      code: result.code,
      success: result.success,
      message: result.success ? '语言配置设置成功' : result.message,
      data: result.data || null,
    });
  } catch (error) {
    console.error('设置语言配置接口错误:', error);
    return res.status(500).json({
      code: 500,
      success: false,
      message: '服务器内部错误',
      data: null,
    });
  }
};

// GET /api/lang/get - 获取语言配置
exports.langGet = async (req, res) => {
  try {
    const LANG_CONFIG_CACHE_KEY = 'global_lang_config';
    const result = getObjectFromCache(LANG_CONFIG_CACHE_KEY);

    if (result.success && result.data) {
      return res.status(200).json({
        code: 200,
        success: true,
        message: '获取语言配置成功',
        data: result.data,
      });
    } else {
      // 返回默认配置
      const defaultLangConfig = {
        default: 'en',
        available: ['en', 'zh-CN', 'zh-TW', 'es', 'fr', 'de', 'ja', 'ko'],
        current: 'en',
        rtl: false,
        locale: 'en-US',
        currency: 'USD',
        timezone: 'UTC',
        dateFormat: 'YYYY-MM-DD',
        timeFormat: '24h',
        timestamp: Date.now(),
        source: 'default',
      };

      return res.status(200).json({
        code: 200,
        success: true,
        message: '缓存中无数据，返回默认配置',
        data: defaultLangConfig,
      });
    }
  } catch (error) {
    console.error('获取语言配置接口错误:', error);
    return res.status(500).json({
      code: 500,
      success: false,
      message: '服务器内部错误',
      data: null,
    });
  }
};
